package com.ihisomp.filter;

import com.ihisomp.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 标题: AuthenticationFilter.java
 * 业务描述: 认证拦截器类
 * 作者: zy
 * 日期: 2021/9/10
 * 版本: V1.0
 */
@Component
public class AuthenticationFilter extends HandlerInterceptorAdapter {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 请求端带上token
        // 是否登录
        boolean isLogin = false;
        // 获取请求头 Authorization: Bearer jwtToken
        final String authHeader = request.getHeader("Authorization");
        // 判断是否有token，注意 Bearer 后面有空格
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            // 截取获取jwtToken
            final String token = authHeader.substring(7);
            // 解析
            Claims claims = jwtUtil.parseJWT(token);
            if (claims != null) {
                if ((Boolean) claims.get("isLogin")) {
                    // 已登录
                    isLogin = true;
                }
            }
        }

        if (!isLogin) {
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setStatus(401);
            response.getWriter().write("未通过身份认证");
        }
        return isLogin;
    }
}
